const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const { queryResourcesPath } = require('./utils');
const resourcesPath =  queryResourcesPath();

// if (!resourcesPath.length) {
//   console.log(chalk.red('入口配置错误，请重新配置plugin.yaml'));
//   process.exit();
// }

const customEntry = {}; const customEntryHtml = [];

resourcesPath.forEach((item) => {
  const itemPath = item.path;
  const itemName = item.name;
  const entry = itemPath.substring(itemPath.lastIndexOf('/') + 1, itemPath.length);
  const entryPath = itemPath;
  customEntry[entry] = {
    import: path.resolve(`${__dirname}/resources/${entryPath}`),
    dependOn: 'tdesign',
  };
  customEntry.tdesign = 'tdesign-vue/dist/tdesign.min.js';

  customEntryHtml.push(new HtmlWebpackPlugin({
    title: itemName,
    filename: `${itemPath}.html`,
    template: path.resolve(`${__dirname}/resources/pages/index.html`),
    chunks: [entry, 'tdesign'],
  }));
});

const config = {
  entry: customEntry,
  output: {
    path: path.resolve(`${__dirname}/resources/dist`),
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].js',
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }, {
        test: /\.vue$/,
        loader: 'vue-loader',
      }, {
        test: /\.css$/,
        use: ['vue-style-loader', 'css-loader'],
      }, {
        test: /\.less$/i,
        use: ['style-loader', 'css-loader', 'less-loader'],
      }, {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 25000,
          },
        },
      },
    ],
  },
  plugins: [
    new VueLoaderPlugin(),
  ].concat(customEntryHtml),
  devServer: {
    allowedHosts: 'all',
    port: 8889,
    client: {
      webSocketURL: {
        hostname: process.env.UPGRADER_HOST,
        pathname: `/explorer/${process.env.UPGRADER_USER_ID}`,
        port: process.env.UPGRADER_PORT,
        protocol: process.env.UPGRADER_PROTROL,
      },
    },
  },
};

module.exports = config;
